package service

import (
	"context"
	"github.com/spf13/cast"
	"log"
	"nearby/biz/common"
	"nearby/biz/domain/entity"
	domainService "nearby/biz/domain/service"
	"nearby/biz/model"
)

type CreateCommentService struct {
}

func (ss *CreateCommentService) Execute(ctx context.Context, req *model.CreateCommentRequest) (*model.CreateCommentResponse, error) {
	commentDomainService := domainService.CommentService{}
	user := common.GetUser(ctx)
	commentEntity, err := commentDomainService.ConstructCommentEntity(ctx, domainService.ConstructCommentEntityRequest{
		UserID:     user.UserID,
		EntityID:   cast.ToInt64(req.EntityID),
		EntityType: req.EntityType,
		Content: entity.CommentContent{
			Text: req.Content.Text,
		},
	})
	if err != nil {
		return nil, common.NewBizErr(common.BizErrCode, "发表评论失败", err)
	}
	err = commentEntity.Persist(ctx)
	if err != nil {
		return nil, common.NewBizErr(common.BizErrCode, "发表评论失败", err)
	}
	{
		// 同步更新评论数量
		// fixme 之后考虑性能优化的时候, 可以以发送异步消息的方式进行处理(这个步骤会消耗100ms左右)
		err = commentEntity.SyncCnt(ctx, 1)
		if err != nil {
			log.Printf("commentEntity.SyncCommentCnt fail, err: %+v", err)
		}
	}
	{
		// 装载创建者的信息
		commentEntity.User.HeadURL = user.HeadURL
		commentEntity.User.Nickname = user.Nickname
	}
	vo := commentEntity.ToVo()
	return &model.CreateCommentResponse{
		Meta:    common.MetaOk,
		Comment: *vo,
	}, nil
}
